#!/usr/bin/env python
# -*- coding: utf-8 -*-

__authors__ = ["Lukas Zapletal (lukas.zapletal_gmail_com)"]
__date__ = "2007/08/10"
__copyright__ = """
Copyright (c) 2006, Lukas Zapletal 
All rights reserved.
"""
__license__ = """
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

     * Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

from config import *

from xml.sax import handler
from sets import Set
from os import system
from time import sleep

class FindAlbums(handler.ContentHandler):
    def __init__(self, tags, encoding, network):
        self.searchTags, self.encoding, self.network = tags.lower().split(' '), encoding, network
        self.albums = False
        self.matchesLink = False
        self.matchesTags = False
        self.include = False
        self.buffer = []
        self.tags = []

    def startElement(self, name, attrs):
        if self.albums:
            if self.albums and name.lower() == 'tags':
                # prepare the output buffer
                self.buffer = []
                self.matchesTags = True
            if self.albums and self.include and name.lower() == 'p2plink' and \
                    attrs.get('audioEncoding').lower() == self.encoding and \
                    attrs.get('network').lower() == self.network:
                # prepare the output buffer
                self.buffer = []
                self.matchesLink = True
        else:
            if name.lower() == 'albums':
                self.albums = True

    def endElement(self, name):
        if name.lower() == 'albums':
            self.albums = False
        if name.lower() == 'tags' and self.matchesTags:
            self.tags = "".join(self.buffer).split(' ')
            self.include = self.filter(self.tags)
            self.matchesTags = False
        if name.lower() == 'p2plink' and self.matchesLink:
            link = "".join(self.buffer)
            print "Adding " + link + " (" + " ".join(self.tags) + ")"
            system(command % link)
            sleep(delay_between_execs)
            self.matchesLink = False

    def characters(self,contents):
        self.buffer.append(contents)

    def filter(self, tags):
        t = Set(tags)
        st = Set(self.searchTags)
        return st.issubset(t)

from xml.sax import make_parser
from xml.sax.handler import feature_namespaces

if __name__ == '__main__':

    # Create a parser
    parser = make_parser()

    # Tell the parser we are not interested in XML namespaces
    parser.setFeature(feature_namespaces, 0)

    # Create the handler
    finder = FindAlbums(download_tags, format, 'bittorrent')

    # Tell the parser to use our handler
    parser.setContentHandler(finder)

    # Parse the input
    parser.parse('dbdump.en.xml')

# vim: set sw=4 ts=4 sts=4 sta et ai fenc=utf-8 : #

